package com.tgy.springmvc.util;


import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @Author: tgy
 * @Date: 2020-08-24 10:28
 */
public class RequestUtil {


    public static HttpServletRequest getHttpServletRequest(){

        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    }


    public static void setSession(String key, Object value){


        if (StringUtils.isEmpty(key)){

            return;
        }

        HttpSession session = getHttpServletRequest().getSession();

        if (Objects.isNull(value)){

            session.removeAttribute(key);
            return;
        }

        session.setAttribute(key,value);

    }

    public static Object getSession(String key){

        if (Objects.isNull(key)){

            return null;
        }

        return getHttpServletRequest().getSession().getAttribute(key);
    }
}
